package com.hcb.logsdk.service;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.hcb.logsdk.socketio.listener.IConstants;
import com.hcb.logsdk.util.BroadcastUtil;


/**
 * @author
 *
 */
public class PushLogService extends Service{
	private static final String LOGTAG = PushLogService.class.getSimpleName();
	private static final String ACTION_PREFIX = "com.tuita.sdk";
	private static final String ACTION_START = ACTION_PREFIX + ".START";
	private static final String ACTION_STOP = ACTION_PREFIX + ".STOP";
	private static final String ACTION_SET_TEST = ACTION_PREFIX + ".SET_TEST";
	public PushServerConnection mPushConn;

	public static void setTest(Context ctx, int ifTest) {
		Intent i = new Intent(ctx, PushLogService.class);
		i.setAction(ACTION_SET_TEST);
		i.putExtra("test", ifTest);
		ctx.startService(i);
	}
	public static void startService(Context ctx) {
		Intent i = new Intent(ctx, PushLogService.class);
		i.setAction(ACTION_START);
		ctx.startService(i);
	}
	public static void stopService(Context ctx) {
		Intent i = new Intent(ctx, PushLogService.class);
		i.setAction(ACTION_STOP);
		ctx.stopService(i);
	}


	@Override
	public IBinder onBind(Intent intent) {
		return new LocalBinder();
	}

	public final class LocalBinder extends Binder {
		public PushLogService getService() {
			return PushLogService.this;
		}
	}


	@Override
	public void onCreate() {
		super.onCreate();
		mPushConn = new PushServerConnection(getApplicationContext());
		startForeground();
	}





	@Override
	public void onDestroy() {
		Log.i(LOGTAG, "onDestroy");
//		stopForeground(true);
		stop();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (intent != null) {
			String action = intent.getAction();
			if (action != null) {
				if (action.equals(ACTION_STOP)) {
				} else if (action.equals(ACTION_START)) {
				} else if (action.equals(ACTION_SET_TEST)) {
					// 2 线上 1 预上线 0 测试
//					int test = intent.getIntExtra("test", 2);
//					push_connect(test);
				}
			}
		}
	}


	public void push_connect(int code) {
		mPushConn.push_connect("diskkiller");
	}
	public void stop_connect() {
		mPushConn.stopConnection();
	}
	public void close_connect() {
		mPushConn.closeConnection();
	}

	private void startForeground() {
		Notification note = new Notification(0, null, System.currentTimeMillis());
		note.flags |= Notification.FLAG_NO_CLEAR;
		if (android.os.Build.VERSION.SDK_INT < 18)
			startForeground(134138, note);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}


	public void stop() {
		mPushConn.stopConnection();
//		logclose_connect();
		BroadcastUtil.sendBroadcastToUI(this, IConstants.SERVICE_STOP,null);
	}

}